﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.UI.WebControls;
using Common.Logging;
using Newtonsoft.Json;
using OutDbContext;
using User.Api.BizExtensions;
using User.Api.Dto.Paper;
using User.Api.Helpers;
using static User.Api.Dto.Paper.GetAllResponse;

namespace User.Api.Controllers
{
 //[AllowAnonymous]
    //public class PaperController : ApiController
    //{
    //    private static readonly ILog Logger = LogManager.GetLogger(typeof(PaperController));
    //    private HzfyWeiXinEntities _ctx;

    //    protected override void Initialize(HttpControllerContext controllerContext)
    //    {
    //        _ctx = new HzfyWeiXinEntities();
    //        base.Initialize(controllerContext);
    //    }

    //    protected override void Dispose(bool disposing)
    //    {
    //        _ctx.Dispose();
    //        base.Dispose(disposing);
    //    }

    //    /// <summary>
    //    /// 获取满意度调查列表
    //    /// </summary>
    //    /// <returns></returns>
    //    [HttpGet]
    //    [ActionName("GetAll")]
    //    public GetAllResponse GetAll()
    //    {
    //        var azUser = AzUser.GetInApi(Request);
    //        var userId = azUser.UserId;

    //        // 先查询缴费订单，后查询挂号订单，
    //            //如果存在缴费订单，可以做问卷，如果不存在缴费订单，查询挂号订单，如果存在，可以做问卷；
    //            //问卷有效期为7天；
    //        var sevenDaysAgoDt = System.DateTime.Now.Date.AddDays(-7);
    //        var sevenDaysAgo = sevenDaysAgoDt.ToString("yyyy-MM-dd");
    //        var strToday = DateTime.Now.Date.ToString("yyyy-MM-dd");
    //        List<TreatInfo> list = new List<TreatInfo>();
    //        List<TreatInfo> waitList = new List<TreatInfo>();
    //        List<TreatInfo> completedList = new List<TreatInfo>();
    //        TreatInfo treat = null;

    //        #region 缴费记录

    //        var payState = BillOrderExtensions.PayState.已付款.ToInt32().ToString();
    //        var orderStatus = BillOrderExtensions.OrderStatus.缴费成功.ToInt32();
    //        var billOrders = _ctx.BillOrders.Where(x => x.WxUserId == userId && x.OrderStatus == orderStatus
    //        && x.PayState == payState
    //        && x.CreateTime > sevenDaysAgoDt).ToList(); //7天内缴费成功订单

    //        foreach (var billOrder in billOrders)
    //        {
    //            var prescription = _ctx.BillOrderPrescriptions.FirstOrDefault(x => x.BillId == billOrder.Id);
    //            treat = new TreatInfo
    //            {
    //                DeptName = prescription?.OrderDept ?? "",
    //                DeptId = "",
    //                IsAnswered = false,
    //                OrderType = "1",
    //                OrderId = billOrder.Id.ToString(),
    //                TreatDate = billOrder.CreateTime?.ToString("yyyy-MM-dd") ?? DateTime.Now.ToString("yyyy-MM-dd")
    //            };

    //            if (!list.Contains(treat))
    //                list.Add(treat);
    //        }

    //        #endregion

    //        #region 挂号记录

    //        var billPayState = ApptOrderExtensions.PayState.已付款.ToInt32().ToString();
    //        var apptOrders = _ctx.ApptOrders.IsStatus(ApptOrderExtensions.OrderStatus.取号成功).Where(x => x.WxUserId == userId  && x.PayState == billPayState
    //                    && String.Compare(x.RegDate, sevenDaysAgo, StringComparison.Ordinal) >= 0 && String.Compare(x.RegDate, strToday, StringComparison.Ordinal) < 0).ToList(); //就诊日期7天内成功的挂号订单
    //        foreach (var apptOrder in apptOrders)
    //        {
    //            treat = new TreatInfo
    //            {
    //                DeptName = apptOrder.DeptName,
    //                DeptId = apptOrder.DeptId,
    //                IsAnswered = false,
    //                OrderType = "0",
    //                OrderId = apptOrder.Id.ToString(),
    //                TreatDate = apptOrder.RegDate
    //            };
    //            if (!list.Contains(treat))
    //                list.Add(treat);
    //        }

    //        #endregion

    //        foreach (var treatInfo in list)
    //        {
    //            var todayDt = DateTime.Parse(treatInfo.TreatDate);
    //            var tomorrowDt = todayDt.AddDays(1);
    //            var isExist = _ctx.SIPaperUserAnswers.Any(x => x.WxUserId == userId
    //                  && x.TreatDate >= todayDt && x.TreatDate < tomorrowDt);
    //            if (isExist)
    //            {
    //                treatInfo.IsAnswered = true;
    //                completedList.Add(treatInfo);
    //            }
    //            else
    //            {
    //                waitList.Add(treatInfo);
    //            }
    //        }

    //        var response = new GetAllResponse
    //        {
    //            ResultCode = "0",
    //            ResultMsg = "",
    //            WaitingPapers = waitList.OrderByDescending(y => y.TreatDate).ToList(),
    //            CompletePapers = completedList.OrderByDescending(y => y.TreatDate).ToList()
    //        };
    //        return response;
    //    }

    //    /// <summary>
    //    /// 获取满意度调查明细
    //    /// </summary>

    //    /// <returns></returns>
    //    [HttpGet]
    //    [ActionName("GetInvestigatePaper")]
    //    public GetInvestigatePaperResponse GetInvestigatePaper(string deptName, string treatDate, string orderType, string orderId, string deptId = "")
    //    {
    //        var azUser = AzUser.GetInApi(Request);
    //        var treatRecord = new TreatInfo
    //        {
    //            DeptId = deptId,
    //            DeptName = deptName,
    //            TreatDate = treatDate,
    //            OrderType = orderType,
    //            OrderId = orderId
    //        };

    //        var response = new GetInvestigatePaperResponse
    //        {
    //            ResultCode = "0",
    //            TreatRecord = treatRecord,
    //            QuestionList = _ctx.SIPaperQuestions.Where(x => x.RecStatus == 0).OrderBy(x => x.SqNo)
    //            .Select(x => new GetInvestigatePaperResponse.Question {
    //                Id = x.Id,
    //                Content = x.Content
    //             }).ToList(),
    //            ResultMsg = ""
    //        };

    //        return response;
    //    }

    //    /// <summary>
    //    /// 提交满意度调查
    //    /// </summary>
    //    /// <returns></returns>
    //    [HttpPost]
    //    [ActionName("SubmitPingJia")]
    //    public SubmitPingJiaResponse SubmitPingJia(PaperRequest request)
    //    {
            
    //        try
    //        {
    //            var azUser = AzUser.GetInApi(Request);
    //            var wxUserId = azUser.UserId;
    //            var treatDateDt = new DateTime();
    //            bool isChecked = !string.IsNullOrEmpty(request.treatDate) && DateTime.TryParse(request.treatDate, out treatDateDt)
    //                && request.items != null && request.items.Count>0;

    //            if (isChecked)
    //            {
    //                var isExists = _ctx.SIPaperUserAnswers.Any(x => x.TreatDate == treatDateDt && x.WxUserId == wxUserId);
    //                if (!isExists)
    //                {
    //                    var userAnswer = new SIPaperUserAnswer
    //                    {
    //                        WxUserId = wxUserId,
    //                        TreatDate = treatDateDt,
    //                        DeptId = request.deptId ?? "",
    //                        DeptName = request.deptName ?? "",
    //                        OrderType = string.IsNullOrEmpty(request.orderType) ? -1 : request.orderType.ToInt32OrDefault(),
    //                        OrderId = string.IsNullOrEmpty(request.orderId) ? -1 : request.orderId.ToInt32OrDefault(),
    //                        Suggestion = System.Net.WebUtility.UrlDecode(request.answer)  ?? "",
    //                        Phone = System.Net.WebUtility.UrlDecode(request.phone) ?? "",
    //                        SubmitDt = DateTime.Now
    //                    };
    //                    //  userAnswer.SatisfiedDept = sDept ?? "";
    //                    // userAnswer.SatisfiedDoctor = sDoctor ?? "";
    //                    // userAnswer.Name = name ?? "";
    //                    _ctx.SIPaperUserAnswers.Add(userAnswer);
    //                    _ctx.SaveChanges();

    //                    var userAnswerId = userAnswer.Id;
    //                    for (var i = 0; i < request.items.Count; i++)
    //                    {
    //                        var userAnswerItem = new SIPaperUserAnswerItem
    //                        {
    //                            UserAnswerId = userAnswerId,
    //                            QuestionId = request.items[i].id.ToInt32OrDefault(),
    //                            AnswerItemId = request.items[i].answer.ToInt32OrDefault(),
    //                            RecCreateDt = DateTime.Now
    //                        };
    //                        _ctx.SIPaperUserAnswerItems.Add(userAnswerItem);
    //                    }
    //                    _ctx.SaveChanges();
    //                }
    //            }

    //        }
    //        catch (Exception ex)
    //        {
    //            Logger.ErrorFormat("提交满意度调查 出错，原因：{0}",ex.Message);

    //            return new SubmitPingJiaResponse()
    //            {
    //                ResultCode = "1",
    //                ResultMsg = ""
    //            };
    //        }

    //        return new SubmitPingJiaResponse()
    //        {
    //            ResultCode = "0",
    //            ResultMsg = ""
    //        };
    //    }
    //}

}
